package com.bitmain.mmst.common.util;

import javax.servlet.ServletContext;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.web.context.WebApplicationContext;

/**
 * 
 *
 * @author Richard - rui.wu@bitmain.com
 * @since 2016年7月17日
 *
 */
public class SpringContextHolder implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;
	private static WebApplicationContext webApplicationContext;
	private static ServletContext servletContext;

	/* (non-Javadoc)
	 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextHolder.applicationContext = applicationContext;
		SpringContextHolder.webApplicationContext = (WebApplicationContext) applicationContext;
		SpringContextHolder.servletContext = webApplicationContext.getServletContext();
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	public static String getRealPath(String path) {
		checkApplicationContext();
		return servletContext.getRealPath(path);
	}
	
	public static <T> T getBean(String name, Class<T> type) {
		checkApplicationContext();
		return applicationContext.getBean(name, type);
	}
	
	public static void publishApplicationEvent(ApplicationEvent event) {
		checkApplicationContext();
		applicationContext.publishEvent(event);
	}
	
	private static void checkApplicationContext() {
		if (null == applicationContext) {
			throw new IllegalStateException("ApplicaitonContext未注入,请在Spring配置文件中定义SpringContextHolder");
		}
	}
}
